#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>

using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
    
};

int res;
int dfs(TreeNode* cur)
{
    if (cur == nullptr)  return 0;
    int left = dfs(cur->left);
    int right = dfs(cur->right);
    res = max(res, left + right + 1);
    return max(left, right) + 1;
}

int diameterOfBinaryTree(TreeNode* root) {
    res = 0;
    dfs(root);
    return res - 1;
}